const dayjs = require('dayjs');
/**
 * Crm Store
 * 负责管理crm相关的状态和数据处理
 */

import { observable, action  } from 'mobx-miniprogram';

// CRM模块Store
export const crmStore = observable({
  // 客户列表数据
  customerList: [],
  
  // 联系人列表数据
  contactList: [],
  
  // 当前选中的客户
  currentCustomer: null,
  
  // 当前选中的联系人
  currentContact: null,
  
  // 客户分类
  customerCategories: [],
  
  // 跟进记录
  followUpRecords: [],
  
  // 客户过滤条件
  customerFilter: {
    category: '',
    status: '',
    level: '',
    searchKey: '',
    sortBy: 'createTime',
    sortOrder: 'desc'
  },
  
  // 联系人过滤条件
  contactFilter: {
    customerId: '',
    position: '',
    importance: '',
    searchKey: ''
  },
  
  // 统计数据
  statistics: {
    totalCustomers: 0,
    totalContacts: 0,
    potentialCustomers: 0,
    signedCustomers: 0,
    customersByLevel: {},
    followUpThisWeek: 0,
    followUpNextWeek: 0,
    recentlyAddedCustomers: 0
  },
  
  // 页面加载状态
  loading: {
    customers: false,
    contacts: false,
    followUps: false
  },
  
  // 计算属性：筛选后的客户列表
  get filteredCustomers() {
    if (!this.customerList.length) return [];
    
    let filtered = [...this.customerList];
    
    // 根据分类筛选
    if (this.customerFilter.category) {
      filtered = filtered.filter(c => c.category === this.customerFilter.category);
    }
    
    // 根据状态筛选
    if (this.customerFilter.status) {
      filtered = filtered.filter(c => c.status === this.customerFilter.status);
    }
    
    // 根据客户级别筛选
    if (this.customerFilter.level) {
      filtered = filtered.filter(c => c.level === this.customerFilter.level);
    }
    
    // 根据关键词搜索
    if (this.customerFilter.searchKey) {
      const key = this.customerFilter.searchKey.toLowerCase();
      filtered = filtered.filter(c => 
        c.name.toLowerCase().includes(key) || 
        c.description.toLowerCase().includes(key) ||
        c.industry.toLowerCase().includes(key)
      );
    }
    
    // 排序
    filtered.sort((a, b) => {
      const field = this.customerFilter.sortBy;
      const order = this.customerFilter.sortOrder === 'asc' ? 1 : -1;
      
      if (field === 'createTime' || field === 'lastContactTime') {
        const dateA = dayjs(a[field]);
        const dateB = dayjs(b[field]);
        return dateA > dateB ? order : -order;
      }
      
      return a[field] > b[field] ? order : -order;
    });
    
    return filtered;
  },
  
  // 计算属性：筛选后的联系人列表
  get filteredContacts() {
    if (!this.contactList.length) return [];
    
    let filtered = [...this.contactList];
    
    // 根据客户ID筛选
    if (this.contactFilter.customerId) {
      filtered = filtered.filter(c => c.customerId === this.contactFilter.customerId);
    }
    
    // 根据职位筛选
    if (this.contactFilter.position) {
      filtered = filtered.filter(c => c.position === this.contactFilter.position);
    }
    
    // 根据重要性筛选
    if (this.contactFilter.importance) {
      filtered = filtered.filter(c => c.importance === this.contactFilter.importance);
    }
    
    // 根据关键词搜索
    if (this.contactFilter.searchKey) {
      const key = this.contactFilter.searchKey.toLowerCase();
      filtered = filtered.filter(c => 
        c.name.toLowerCase().includes(key) || 
        c.email.toLowerCase().includes(key) ||
        c.phone.includes(key) ||
        c.position.toLowerCase().includes(key)
      );
    }
    
    return filtered;
  },
  
  // 计算属性：获取需要跟进的客户
  get customersNeedFollowUp() {
    const now = dayjs();
    const thirtyDaysAgo = now.subtract(30, 'day');
    
    return this.customerList.filter(c => {
      // 已签约的客户，超过30天未跟进
      if (c.status === 'signed') {
        const lastContactTime = dayjs(c.lastContactTime);
        return lastContactTime.isBefore(thirtyDaysAgo);
      }
      
      // 潜在客户，超过15天未跟进
      if (c.status === 'potential') {
        const lastContactTime = dayjs(c.lastContactTime);
        const fifteenDaysAgo = now.subtract(15, 'day');
        return lastContactTime.isBefore(fifteenDaysAgo);
      }
      
      return false;
    });
  },
  
  // Action: 设置客户列表
  setCustomerList: action(function(customers) {
    this.customerList = customers;
    this.updateStatistics();
  }),
  
  // Action: 设置联系人列表
  setContactList: action(function(contacts) {
    this.contactList = contacts;
    this.updateStatistics();
  }),
  
  // Action: 设置跟进记录
  setFollowUpRecords: action(function(records) {
    this.followUpRecords = records;
    this.updateStatistics();
  }),
  
  // Action: 更新统计数据
  updateStatistics: action(function() {
    const now = dayjs();
    const weekStart = now.startOf('week');
    const weekEnd = weekStart.endOf('week');
    
    const nextWeekStart = weekEnd.add(1, 'day');
    const nextWeekEnd = nextWeekStart.add(6, 'day');
    
    const oneMonthAgo = now.subtract(1, 'month');
    
    // 按客户级别统计
    const customersByLevel = {};
    ['A', 'B', 'C', 'D'].forEach(level => {
      customersByLevel[level] = this.customerList.filter(c => c.level === level).length;
    });
    
    // 统计本周和下周需要跟进的数量
    const followUpThisWeek = this.followUpRecords.filter(record => {
      const planTime = dayjs(record.planTime);
      return planTime.isAfter(weekStart) && planTime.isBefore(weekEnd);
    }).length;
    
    const followUpNextWeek = this.followUpRecords.filter(record => {
      const planTime = dayjs(record.planTime);
      return planTime.isAfter(nextWeekStart) && planTime.isBefore(nextWeekEnd);
    }).length;
    
    // 统计近一个月新增的客户
    const recentlyAddedCustomers = this.customerList.filter(c => {
      const createTime = dayjs(c.createTime);
      return createTime.isAfter(oneMonthAgo);
    }).length;
    
    this.statistics = {
      totalCustomers: this.customerList.length,
      totalContacts: this.contactList.length,
      potentialCustomers: this.customerList.filter(c => c.status === 'potential').length,
      signedCustomers: this.customerList.filter(c => c.status === 'signed').length,
      customersByLevel,
      followUpThisWeek,
      followUpNextWeek,
      recentlyAddedCustomers
    };
  }),
  
  // Action: 设置当前客户
  setCurrentCustomer: action(function(customerId) {
    this.currentCustomer = this.customerList.find(c => c._id === customerId) || null;
    
    // 如果设置了当前客户，自动筛选该客户的联系人
    if (this.currentCustomer) {
      this.setContactFilter({ customerId: customerId });
    }
  }),
  
  // Action: 设置当前联系人
  setCurrentContact: action(function(contactId) {
    this.currentContact = this.contactList.find(c => c._id === contactId) || null;
  }),
  
  // Action: 添加客户
  addCustomer: action(function(customer) {
    this.customerList.push(customer);
    this.updateStatistics();
  }),
  
  // Action: 更新客户
  updateCustomer: action(function(customerId, data) {
    const index = this.customerList.findIndex(c => c._id === customerId);
    if (index >= 0) {
      this.customerList[index] = {...this.customerList[index], ...data};
      
      // 如果当前选中的是这个客户，也更新currentCustomer
      if (this.currentCustomer && this.currentCustomer._id === customerId) {
        this.currentCustomer = {...this.currentCustomer, ...data};
      }
      
      this.updateStatistics();
    }
  }),
  
  // Action: 删除客户
  deleteCustomer: action(function(customerId) {
    const index = this.customerList.findIndex(c => c._id === customerId);
    if (index >= 0) {
      this.customerList.splice(index, 1);
      
      // 如果当前选中的是这个客户，清空currentCustomer
      if (this.currentCustomer && this.currentCustomer._id === customerId) {
        this.currentCustomer = null;
      }
      
      // 同时删除该客户的所有联系人
      this.contactList = this.contactList.filter(contact => contact.customerId !== customerId);
      
      // 如果当前选中的联系人属于被删除的客户，也清空currentContact
      if (this.currentContact && this.currentContact.customerId === customerId) {
        this.currentContact = null;
      }
      
      this.updateStatistics();
    }
  }),
  
  // Action: 添加联系人
  addContact: action(function(contact) {
    this.contactList.push(contact);
    this.updateStatistics();
  }),
  
  // Action: 更新联系人
  updateContact: action(function(contactId, data) {
    const index = this.contactList.findIndex(c => c._id === contactId);
    if (index >= 0) {
      this.contactList[index] = {...this.contactList[index], ...data};
      
      // 如果当前选中的是这个联系人，也更新currentContact
      if (this.currentContact && this.currentContact._id === contactId) {
        this.currentContact = {...this.currentContact, ...data};
      }
      
      this.updateStatistics();
    }
  }),
  
  // Action: 删除联系人
  deleteContact: action(function(contactId) {
    const index = this.contactList.findIndex(c => c._id === contactId);
    if (index >= 0) {
      this.contactList.splice(index, 1);
      
      // 如果当前选中的是这个联系人，清空currentContact
      if (this.currentContact && this.currentContact._id === contactId) {
        this.currentContact = null;
      }
      
      this.updateStatistics();
    }
  }),
  
  // Action: 添加跟进记录
  addFollowUpRecord: action(function(record) {
    this.followUpRecords.push(record);
    
    // 更新客户的最后跟进时间
    if (record.customerId) {
      const index = this.customerList.findIndex(c => c._id === record.customerId);
      if (index >= 0) {
        this.customerList[index].lastContactTime = record.createTime;
        
        // 如果当前选中的是这个客户，也更新currentCustomer
        if (this.currentCustomer && this.currentCustomer._id === record.customerId) {
          this.currentCustomer.lastContactTime = record.createTime;
        }
      }
    }
    
    this.updateStatistics();
  }),
  
  // Action: 设置客户分类
  setCustomerCategories: action(function(categories) {
    this.customerCategories = categories;
  }),
  
  // Action: 设置客户过滤条件
  setCustomerFilter: action(function(filter) {
    this.customerFilter = {...this.customerFilter, ...filter};
  }),
  
  // Action: 清空客户过滤条件
  clearCustomerFilter: action(function() {
    this.customerFilter = {
      category: '',
      status: '',
      level: '',
      searchKey: '',
      sortBy: 'createTime',
      sortOrder: 'desc'
    };
  }),
  
  // Action: 设置联系人过滤条件
  setContactFilter: action(function(filter) {
    this.contactFilter = {...this.contactFilter, ...filter};
  }),
  
  // Action: 清空联系人过滤条件
  clearContactFilter: action(function() {
    this.contactFilter = {
      customerId: '',
      position: '',
      importance: '',
      searchKey: ''
    };
  }),
  
  // Action: 设置加载状态
  setLoading: action(function(key, isLoading) {
    if (this.loading[key] !== undefined) {
      this.loading[key] = isLoading;
    }
  })
}); 